# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(pROC)
library(egg)
library(optparse)
library(tidyverse)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--base", default = "metabo_base.R", type = "character", help = "metabo base R file")

)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)
source(opt$base)

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote")) %>%
  mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote)))
head(sampleInfo)

diffNames <- getDiffNames()

data <- read_csv(opt$i) %>%
  select(-c("HMDB", "KEGG", "Class")) %>%
  filter(Metabolite %in% diffNames) %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value") %>%
  inner_join(sampleInfo, by = c("SampleID"))

data

getRoc <- function(name) {
  x <- data[name] %>% unlist()
  y <- data$ClassNote
  rocRs <- roc(y, x, ci = T)
  return(list(name = name, roc = rocRs))
}

rocs <- diffNames %>%
  map(getRoc)

aucData <- rocs %>%
  map_dfr(function(rocList) {
    rocRs <- rocList$roc
    name <- rocList$name
    auc <- round(rocRs$auc, 3)
    ci <- rocRs$ci
    ci1 <- ci[1]
    ci2 <- ci[3]
    pointData <- coords(rocRs, "best", transpose = FALSE) %>%
      round(3)
    pointData <- if (is.vector(pointData) && length(pointData) > 1) {
     bind_rows(pointData)
    }else {
      pointData %>%
        as.data.frame()
    }

    return(data.frame(Metabolite = name, AUC = auc, CI1 = ci1, CI2 = ci2, Thres = pointData$threshold,
                      Specificity = pointData$specificity, Sensitivity = pointData$sensitivity))
  }) %>%
  arrange(desc(AUC))

aucData

outFileName <- "Single_Met_ROC.csv"
write.csv(aucData, outFileName, row.names = F)









